<?php
namespace module\home\model;

use DataModel;
use Auth;
require_once APP_DIR . '/library/DataModel.php';
require_once APP_DIR . '/library/Auth.php';

/**
 * Share Model class 
 *
 * @package yasns
 * @subpackage model
 */
class Share extends DataModel
{
	protected
	   $_table = 'share',
	   $_pk = 'share_id';

	/**
	 * find all available shares by specified type
	 * 
	 * @param string $type share type
	 * @param int $count total number of resutls to return
	 * @return array
	 */
	public static function findByType($type, $count = null)
	{		
		$conn = DataModel::getConnection();
		$table = "share";
		$fieldShareType = "share_type";
		$sortby = "share_datetime DESC";
		
		// check if count is empty
		$limit = (isset($count)) ? "limit {$count}" : '';
		
		$stmt = $conn->prepare(	"select * from {$table} LEFT JOIN account on share.account_id = account.account_id " .
										"where {$fieldShareType} = ? " .
										"ORDER BY {$sortby} {$limit}");

		$stmt->execute( array($type) );
		$rows = $stmt->fetchAll();
		
		if (!$rows) { return null; }
		
		return $rows;
	}
	
	/** 
	 * find all available shares
	 * 
	 * @param int $count number of messages to return
	 * @return array
	 */
	public static function findAll($count = null)
	{
		$conn = DataModel::getConnection();
		$table = "share";
		$join = "LEFT JOIN account ON share.account_id = account.account_id";
		$sortby = "share_datetime DESC";
		
		// check if count is empty
		$limit = (isset($count)) ? "limit {$count}" : '';
		
		$stmt = $conn->prepare(	"select * from {$table} {$join} " .
										"ORDER BY {$sortby} {$limit}");
										
		$stmt->execute();
		$rows = $stmt->fetchAll();
		
		if (!$rows) { return null; }

		return $rows;
	}
	
	
	/**
	 * find all available shares by specified user
	 * 
	 * @param int $account_id
	 * @return array 
	 */
	public static function findByAccountId($account_id, $count = null, $type = null)
	{
		$conn = DataModel::getConnection();
		$table = "share";
		$fieldAccountId = "account_id";
		$sortby = "share_datetime DESC";
		
		// check if count is empty
		$limit = (isset($count)) ? "limit {$count}" : '';
		$where = "where {$fieldAccountId} = ? ";
		$params = array($account_id);
		
		if($type) {
			$where .= " AND share_type = ?";
			$params[] = $type;
		}
		
		$stmt = $conn->prepare(	"select * from {$table} " .
								"{$where}" .
								"ORDER BY {$sortby} {$limit}");


		$stmt->execute( $params );
		$rows = $stmt->fetchAll();
		
		if (!$rows) { return null; }
		
		return $rows;
	}
}
?>